/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Estadisticas.java
 *
 * Created on 10-mar-2012, 23:38:02
 */
package formularios;

import Reportes.MetodosImpresion;
import clases.ConversorRSaDefaultTableModel;
import clases.abmBovino;
import clases.conexion;
import clases.graficos;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
 *
 * @author Ele
 */
public class Estadisticas extends javax.swing.JDialog {
int identificacion=0;
    /** Creates new form Estadisticas */
    public Estadisticas(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setTitle("Estadisticas");
       layerPanel.setVisible(false);
       jLabel3.setVisible(false);
       jLabel4.setVisible(false);
       jButton1.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PedirIdentificacion = new javax.swing.JDialog();
        jLabel2 = new javax.swing.JLabel();
        tfId = new javax.swing.JTextField();
        btnAcepId = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbEstadisticas = new javax.swing.JComboBox();
        layerPanel = new javax.swing.JLayeredPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaEstadistica = new javax.swing.JTable();
        imagen = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        PedirIdentificacion.setTitle("Numero identificación del animal");
        PedirIdentificacion.setModal(true);

        jLabel2.setText("N° Identificacion:");

        btnAcepId.setText("Aceptar");
        btnAcepId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcepIdActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PedirIdentificacionLayout = new javax.swing.GroupLayout(PedirIdentificacion.getContentPane());
        PedirIdentificacion.getContentPane().setLayout(PedirIdentificacionLayout);
        PedirIdentificacionLayout.setHorizontalGroup(
            PedirIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PedirIdentificacionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PedirIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAcepId)
                    .addGroup(PedirIdentificacionLayout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        PedirIdentificacionLayout.setVerticalGroup(
            PedirIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PedirIdentificacionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PedirIdentificacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAcepId)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Estadisiticas");
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones de Estadisticas"));

        jLabel1.setText("Seleccione el tipo de estadistica:");

        cbEstadisticas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione una estadistica", "Porcentajes por estado de animal", "Linea de crecimiento peso por animal", "Cantidad de animales por fecha" }));
        cbEstadisticas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbEstadisticasItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(cbEstadisticas, 0, 496, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbEstadisticas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        tablaEstadistica.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Id Estado", "Descripcion", "Total", "Porcentaje"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tablaEstadistica);
        tablaEstadistica.getColumnModel().getColumn(0).setResizable(false);
        tablaEstadistica.getColumnModel().getColumn(1).setResizable(false);
        tablaEstadistica.getColumnModel().getColumn(2).setResizable(false);
        tablaEstadistica.getColumnModel().getColumn(3).setResizable(false);

        jScrollPane2.setBounds(10, 350, 670, 120);
        layerPanel.add(jScrollPane2, javax.swing.JLayeredPane.DEFAULT_LAYER);
        imagen.setBounds(20, 10, 670, 300);
        layerPanel.add(imagen, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Cantidad de hembras:");
        jLabel3.setBounds(10, 320, 140, 20);
        layerPanel.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setBounds(150, 320, 40, 20);
        layerPanel.add(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton1.setText("Imprimir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.setBounds(533, 320, 140, 23);
        layerPanel.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(layerPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(layerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-737)/2, (screenSize.height-612)/2, 737, 612);
    }// </editor-fold>//GEN-END:initComponents
  public void Conectar(){
        try{
            mdbc = new conexion();
            mdbc.init();
            Connection conn= mdbc.getMyConnection();
            stmt = conn.createStatement();
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos","Error",JOptionPane.ERROR_MESSAGE);
        }
    }
    
     private void CrearTabla(String sql, JTable tabla){
      
          try {
            Conectar();
            ResultSet rs = stmt.executeQuery(sql);

            tabla.setModel(modelo);
            tabla.setAutoResizeMode(tabla.AUTO_RESIZE_ALL_COLUMNS);
              
                    
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error en la consulta de control preñez" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    private void cbEstadisticasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbEstadisticasItemStateChanged
        if (cbEstadisticas.getSelectedIndex() == 0) {
            layerPanel.setVisible(false);
            jLabel3.setVisible(false);
            jLabel4.setVisible(false);
            jButton1.setVisible(false);
        } else {
            if (cbEstadisticas.getSelectedIndex() == 1) {
                GenerarGraficoTorta();
                jLabel3.setVisible(true);
                jLabel4.setVisible(true);
                jLabel4.setText(String.valueOf(new abmBovino().GetHembras()));
                jButton1.setVisible(true);
            } else {
                if (cbEstadisticas.getSelectedIndex() == 2) {
                    PedirIdentificacion.setSize(350, 150);
                    PedirIdentificacion.setLocationRelativeTo(this);
                    PedirIdentificacion.setVisible(true);
                    PedirIdentificacion.setResizable(false);
                    jLabel3.setVisible(false);
                    jLabel4.setVisible(false);
                    jButton1.setVisible(false);
                } else {
                    if (cbEstadisticas.getSelectedIndex() == 3) {
                        GenerarBarraStock();
                        jLabel3.setVisible(false);
                        jLabel4.setVisible(false);
                    }
                    jButton1.setVisible(false);
                }
            }
        }
    }//GEN-LAST:event_cbEstadisticasItemStateChanged

    private void btnAcepIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcepIdActionPerformed
        int id = Integer.parseInt(tfId.getText().trim());
        System.out.println(id);
        if (String.valueOf(id).equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor completar el número de identificación", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            if (new abmBovino().ExisteBovino(id)) {
                //tfId.setText("");
                //PedirIdentificacion.setVisible(false);
                PedirIdentificacion.dispose();
                layerPanel.setVisible(true);
                GenerarLineaCrecPeso(id, imagen, tablaEstadistica);
            } else {
                JOptionPane.showMessageDialog(null, "El número de identificación ingresado no existe", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnAcepIdActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
            try {
                new MetodosImpresion().ReporteCantidadAnimales();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Estadisticas.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Estadisticas.class.getName()).log(Level.SEVERE, null, ex);
            }
         
    }//GEN-LAST:event_jButton1ActionPerformed

   public void GenerarGraficoTorta(){
    
    String comando= "select b.idestadoanimal , e.descripcion , count(*) as total, "
                + " round(((count(*)  * 100)/ (select count(*) from bovino where b.idestadoanimal<=4)),2) as porcentaje"
                + " from bovino b , estadoanimal e where b.idestadoanimal>=0 and b.idestadoanimal<=4 "
                + "and b.idestadoanimal= e.idestadoanimal and b.sexo='H'group by b.idestadoanimal";
     
     
     
    DefaultPieDataset data = new DefaultPieDataset();
        
        try{
            layerPanel.setVisible(true);
            Conectar();
            ResultSet rs = stmt.executeQuery(comando);
             rs.beforeFirst();
             
             while(rs.next()){
                 
                         String estado= rs.getString("descripcion");
                         String porcentaje = rs.getString("porcentaje");
                         if (estado.equals("sin control"))
                             estado="sin control";
                         data.setValue(estado+":"+porcentaje,Float.parseFloat(porcentaje));
             }
        
        
        JFreeChart chart3 = ChartFactory.createPieChart3D("Estadistica por estado animal", data, false, false, false);
        PiePlot3D plot3 = (PiePlot3D) chart3.getPlot();
        plot3.setForegroundAlpha(0.6f);
        plot3.setCircular(true);
        
        
        BufferedImage image = chart3.createBufferedImage(665,280);
        imagen.setIcon(new ImageIcon(image));

     
        new ConversorRSaDefaultTableModel().EstadisticaEstadoAnimal(tablaEstadistica);
        }
              
        catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
        }
}
 
   
   
    public void GenerarBarraStock(){
    
    String comando= "SELECT fecha, count(identificacion) as cantidad "
            + "FROM controles c where idControl=2 group by fecha";
     
     
     
    DefaultPieDataset data = new DefaultPieDataset();
        
        try{
            layerPanel.setVisible(true);
            Conectar();
            ResultSet rs = stmt.executeQuery(comando);
             rs.beforeFirst();
             
             while(rs.next()){
                    
                         String fecha= rs.getString("fecha");
                         String porcentaje = rs.getString("cantidad");
                         data.setValue(porcentaje+" animales el "+fecha,Float.parseFloat(porcentaje));
             }
        
                
        JFreeChart chart3 = ChartFactory.createPieChart3D("Cantidad de animales por fecha",data,false,false,false);
              
        PiePlot3D plot3 = (PiePlot3D) chart3.getPlot();
        plot3.setForegroundAlpha(0.6f);
        plot3.setCircular(true);
        
        
        BufferedImage image = chart3.createBufferedImage(665,280);
        imagen.setIcon(new ImageIcon(image));

     
       // new ConversorRSaDefaultTableModel().EstadisticaEstadoAnimal(tablaEstadistica);
        }
              
        catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
        }
}
   
   public void GenerarLineaCrecPeso(int id, JLabel a, JTable te){
       String consulta= "SELECT dayofyear(c.fecha) as Fecha_Control , c.detalle as Peso FROM controles c where idcontrol=4 and identificacion='"+id+"' order by fecha asc";
       String consulta1= "SELECT c.fecha as Fecha_Control , dayofyear(c.fecha) as Dia_Año , c.detalle as Peso FROM controles c where idcontrol=4 and identificacion='"+id+"' order by fecha asc";
       XYSeries series = new XYSeries("Crecimiento de peso por animal");
    
       
       
       try{
       
            Conectar();
            ResultSet rs = stmt.executeQuery(consulta);
             rs.beforeFirst();
             
             while(rs.next()){
                 
                         int dia= Integer.parseInt(rs.getString("Fecha_Control"));
                         double peso = Double.parseDouble(rs.getString("Peso"));
                         series.add(dia,peso);
                        
             }
             XYDataset xyDataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart
("Grafica de crecimiento de peso",  // Title
"Dia del año",           // X-Axis label
 "Peso",           // Y-Axis label
xyDataset,          // Dataset
PlotOrientation.VERTICAL,
true, false, false);

BufferedImage image = chart.createBufferedImage(665,280);
        a.setIcon(new ImageIcon(image));
        
        CrearTabla(consulta1,te);

   }
    catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
        }
   }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws SQLException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Estadisticas dialog = new Estadisticas(new javax.swing.JFrame(), false);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    private conexion mdbc;
    private Statement stmt;
    private DefaultTableModel modelo = new DefaultTableModel();
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JDialog PedirIdentificacion;
    private javax.swing.JButton btnAcepId;
    private javax.swing.JComboBox cbEstadisticas;
    private javax.swing.JLabel imagen;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLayeredPane layerPanel;
    private javax.swing.JTable tablaEstadistica;
    private javax.swing.JTextField tfId;
    // End of variables declaration//GEN-END:variables
}
